package com.t194.config;

import com.t194.util.DbRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
        @Resource
        private DbRealm dbRealm;
        @Bean
        public ShiroFilterFactoryBean shiroFilter(){
            ShiroFilterFactoryBean shiroFilter=new ShiroFilterFactoryBean();
            shiroFilter.setLoginUrl("/login");
            Map<String,String> chainMap=new HashMap<>();
            chainMap.put("/sys/logout","logout");//设置匿名访问
            chainMap.put("/login","anon");
            chainMap.put("/static/**","anon");
            chainMap.put("/webjars/**","anon");
            chainMap.put("/**","authc");//所有地址都需要身份认证
            shiroFilter.setFilterChainDefinitionMap(chainMap);
            shiroFilter.setSecurityManager(securityManager());
            return shiroFilter;
        }
        @Bean
        public DefaultWebSecurityManager securityManager(){
            DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
            securityManager.setRealm(dbRealm);
            return securityManager;
        }
    //                   凭证匹配器
        @Bean
        public HashedCredentialsMatcher credentialsMatcher(){
            HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
            credentialsMatcher.setHashAlgorithmName("md5");
            credentialsMatcher.setHashIterations(1);
            return credentialsMatcher;
        }
}
